<?php
namespace App\Models;

use App\Models\ComModel;

class PayModel extends ComModel
{

    public $tablename;

    public function __construct()
    {
        parent::__construct();
        $this->tablename = 'pay';
    }

    /**
     * 条件查询
     */
    private function _where(&$select, $data)
    {
        if ($data) {
            if (isset($data['type']) && $data['type']) {
                $select->where('type', $data['type']);
            }

            if (isset($data['userid']) && $data['userid']) {
                $select->where('userid', $data['userid']);
            }

            // 时间搜索
            if (isset($data['start']) && $data['start']) {
                $data['end'] = strtotime(date('Y-m-d 23:59:59', $data['end'] ? $data['end'] : time()));
                $data['start'] = strtotime(date('Y-m-d 00:00:00', $data['start']));
                $select->where('inputtime BETWEEN ' . $data['start'] . ' AND ' . $data['end']);
            } elseif (isset($data['end']) && $data['end']) {
                $data['end'] = strtotime(date('Y-m-d 23:59:59', $data['end']));
                $data['start'] = 1;
                $select->where('inputtime BETWEEN ' . $data['start'] . ' AND ' . $data['end']);
            }
        }
        return $data;
    }

    /**
     * 数据分页显示
     */
    public function limit_page($page = 0, $size = 10, $total = 0, $param = [])
    {
        if ($param) {
            $param = esc($param);
        }

        $page = max(1, (int) $page);
        $total = (int) $total;
        unset($param['page']);
        if ($size > 0 && !$total) {
            $select = $this->db->table($this->tablename)->select('count(*) as total');
            $param = $this->_where($select, $param);
            $query = $select->get();
            if (!$query) {
                log_message('error', '数据查询失败：' . $this->tablename);
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->tablename);
        $param = $this->_where($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy('id', 'asc')->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->tablename);
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['addtime_date'] = date('Y-m-d H:i:s', $v['addtime']);
            }
        }
        $param['total'] = $total;
        return [$data, $total, $param];
    }

    //支付记录
    public function add($data)
    {
        if (!$data || !$data['userid']) {
            return false;
        }

        $data = esc($data);

        $idata = array(
            'releted' => $data['ordersn'],
            'userid' => $data['userid'],
            'username' => $data['username'] ?? '',
            'touserid' => $data['touserid'] ?? 0,
            'tousername' => $data['tousername'] ?? '',
            'title' => $data['title'] ?? '',
            'url' => $data['url'] ?? '',
            'money' => $data['money'],
            'type' => $data['type'],
            'status' => 0,
            'result' => '',
            'paytime' => 0,
            'addtime' => time(),
            'note' => $data['note'] ? $data['note'] : '',
        );

        $this->db->table($this->tablename)->insert($idata);
        $id = $this->db->insertID();
        return $id;
    }

    public function del($id)
    {
        ams_clean_xss($id);
    }

    public function getInfo($id)
    {
        ams_clean_xss($id);
    }

    /**
     * 条件查询
     */
    private function _where_config(&$select, $data)
    {
        if ($data) {
       
            if (isset($data['type']) && $data['type']) {
                $select->where('type', $data['type']);
            }

            if (isset($data['code']) && $data['code']) {
                $select->where('code', $data['code']);
            }

            if (isset($data['name']) && $data['name']) {
                $select->like('name', $data['name'], 'both');
            }

            if (isset($data['status']) && ($data['status'] == 1 || $data['status'] == '0')) {
                $select->where('status', $data['status']);
            }

            // 时间搜索
            if (isset($data['start']) && $data['start']) {
                $data['end'] = strtotime(date('Y-m-d 23:59:59', $data['end'] ? $data['end'] : time()));
                $data['start'] = strtotime(date('Y-m-d 00:00:00', $data['start']));
                $select->where('addtime BETWEEN ' . $data['start'] . ' AND ' . $data['end']);
            } elseif (isset($data['end']) && $data['end']) {
                $data['end'] = strtotime(date('Y-m-d 23:59:59', $data['end']));
                $data['start'] = 1;
                $select->where('addtime BETWEEN ' . $data['start'] . ' AND ' . $data['end']);
            }
        }
        return $data;
    }

    /**
     * 数据分页显示
     */
    public function limit_page_config($page = 0, $size = 10, $total = 0, $param = [])
    {
        $page = max(1, (int) $page);
        $total = (int) $total;
        unset($param['page']);
        if ($param) {
            $param = esc($param);
        }
        if ($size > 0 && !$total) {
            $select = $this->db->table($this->tablename . '_config')->select('count(*) as total');
            $param = $this->_where_config($select, $param);
            $query = $select->get();
            if (!$query) {
                log_message('error', '数据查询失败：' . $this->tablename . '_config');
                return [[], $total, $param];
            }
            $data = $query->getRowArray();
            $total = (int) $data['total'];
            $param['total'] = $total;
            unset($select);
            if (!$total) {
                return [[], $total, $param];
            }
        }

        $select = $this->db->table($this->tablename . '_config');
        $param = $this->_where_config($select, $param);
        $size > 0 && $select->limit($size, $size * ($page - 1));
        $query = $select->orderBy('id', 'asc')->get();
        if (!$query) {
            log_message('error', '数据查询失败：' . $this->tablename . '_config');
            return [[], $total, $param];
        }
        $data = $query->getResultArray();
        if ($data) {
            foreach ($data as $k => $v) {
                $data[$k]['addtime_date'] = date('Y-m-d H:i:s', $v['addtime']);
            }
        }
        $param['total'] = $total;
        return [$data, $total, $param];
    }

    //新增和编辑全部数据时验证
    private function _validate_config($data, $id = 0)
    {
        if (!$data) {
            return ams_rt(1, '参数错误');
        }
        ams_clean_xss($data);

        if (!$data['name']) {
            return ams_rt(1, '名称必须填写');
        } elseif (!$data['code']) {
            return ams_rt(1, '标识必须填写');
        } elseif (!$data['keyvalue']) {
            return ams_rt(1, '参数必须填写');
        }

        $flag = $this->field_exitsts($this->tablename . '_config', 'name', $data['name'], $id);
        if ($flag) {
            return ams_rt(1, '名称已存在');
        }

        $flag = $this->field_exitsts($this->tablename . '_config', 'code', $data['code'], $id);
        if ($flag) {
            return ams_rt(1, '标识已存在');
        }

        return ams_rt(0, 'ok', $data);
    }

    //
    public function getCats()
    {
        $rows = $this->db->table($this->tablename . '_config')->select('id,code,name')->get()->getResultArray();
        if (!$rows) {
            $rows = [];
        }
        return $rows;
    }

    //添加支付平台
    public function addConfig($data)
    {
        $odata = $data;
        $rt = $this->_validate_config($data);
        if ($rt['code']) {
            return $rt;
        }
        $data = $rt['data'];
        $data['keyvalue'] = json_encode($data['keyvalue']);
        $data['addtime'] = time();
        $this->db->table($this->tablename . '_config')->insert($data);
        $id = $this->db->insertID();
        if ($id) {
            unset($odata);
            if (isset($data['thumb']) && $data['thumb']) {
                $related = $this->tablename . '_config' . '-' . $id;
                $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
            }
            $data['id'] = $id;
            $data['keyvalue'] = json_decode($data['keyvalue'], true);
            return ams_rt(0, '操作成功', $data);
        }
        return ams_rt(1, '操作失败', $odata);
    }

    //修改支付平台
    public function editConfig($id, $data)
    {
        $odata = $data;
        $id = intval($id);
        $row = $this->db->table($this->tablename . '_config')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在');
        }
        $rt = $this->_validate_config($data, $id);
        if ($rt['code']) {
            return $rt;
        }

        $data = $rt['data'];
        $data['addtime'] = time();
        $data['keyvalue'] = json_encode($data['keyvalue']);
        $flag = $this->db->table($this->tablename . '_config')->where('id', $id)->update($data);

        if (isset($data['thumb']) && $data['thumb']) {
            $related = $this->tablename . '_config' . '-' . $id;
            $this->db->table('attachment')->where('id', intval($data['thumb']))->update(['related' => $related]);
        }

        return ams_rt(0, '操作成功', $odata);
    }

    //删除支付平台
    public function delConfig($id)
    {
        if (!$id) {
            return ams_rt(1, '参数错误');
        }
        $row = $this->db->table($this->tablename . '_config')->select('id,name,code')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在', []);
        }
        $this->db->table($this->tablename . '_config')->where('id', $id)->delete();
        return ams_rt(0, '操作成功', $row);
    }

    public function switchStatus($id)
    {
        $id = intval($id);
        if (!$id) {
            return ams_rt(1, '参数错误');
        }

        $row = $this->db->table($this->tablename . '_config')->select('id,name,code,status')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return ams_rt(1, '数据不存在');
        }
        if ($row['status'] == 1) {
            $status = 0;
        } else {
            $status = 1;
        }
        $this->db->table($this->tablename . '_config')->where('id', $id)->update(['status' => $status]);
        return ams_rt(0, '操作成功', $row);
    }

    public function setdisplayorder($id, $displayorder)
    {
        return $this->displayorder($this->tablename, $id, $displayorder);
    }

    //获取
    public function getInfoId($id)
    {
        $id = intval($id);
        $row = $this->db->table($this->tablename . '_config')->where('id', $id)->get()->getRowArray();
        if (!$row) {
            return null;
        }
        if ($row['thumb']) {
            $att = $this->db->table('attachment')->where('id', intval($row['thumb']))->get()->getRowArray();
            $row['thumb_info'] = $att;
        }
        $row['addtime_date'] = date('Y-m-d H:i', $row['addtime']);
        $row['keyvalue'] = json_decode($row['keyvalue'], true);
        if ($row['keyvalue'] && is_array($row['keyvalue'])) {
            foreach ($row['keyvalue'] as $v) {
                $row['config'][$v['key']] = $v['value'];
            }
        }
        return $row;
    }

    public function getInfoCode($code)
    {
        ams_clean_xss($code);
        $row = $this->db->table($this->tablename . '_config')->where('code', $code)->get()->getRowArray();
        if (!$row) {
            return null;
        }
        if ($row['thumb']) {
            $att = $this->db->table('attachment')->where('id', intval($row['thumb']))->get()->getRowArray();
            $row['thumb_info'] = $att;
        }
        $row['addtime_date'] = date('Y-m-d H:i', $row['addtime']);
        $row['keyvalue'] = json_decode($row['keyvalue'], true);
        if ($row['keyvalue'] && is_array($row['keyvalue'])) {
            foreach ($row['keyvalue'] as $v) {
                $row['config'][$v['key']] = $v['value'];
            }
        }
        return $row;
    }

}
